import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get_it/get_it.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../config/route/bt_app_router.dart';
import '../../config/route/bt_app_router.gr.dart';
import '../../data/stats/bt_log_pages.dart';
import '../../data/stats/bt_log_pv_manger.dart';
import '../../utils/bt_tool_utils.dart';
import '../utils/bt_dialog_utils.dart';
import 'models/bt_login_model.dart';

@RoutePage(name: "btLoginRoute")
class BtLoginPage extends StatefulWidget {
  const BtLoginPage({super.key});

  @override
  State<BtLoginPage> createState() => _BtLoginPageState();
}

class _BtLoginPageState extends State<BtLoginPage> {
  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      routerAtt();
    });
  }

  void routerAtt() async {
    bool opened = await isFirstOpened();
    if (opened) {
      if (!await Permission.appTrackingTransparency.isGranted) {
        Permission.appTrackingTransparency.request();
      }
      setFirstOpened(false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ChangeNotifierProvider(
        create: (context) => BtLoginModel(),
        child: Consumer<BtLoginModel>(builder: (context, model, _) {
          return Stack(
            children: [
              SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: Image.asset(
                  'assets/images/bt_login_bg.png',
                  fit: BoxFit.fill,
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 55,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    InkWell(
                      child: Container(
                        height: 54,
                        margin: const EdgeInsets.only(left: 48, top: 90, right: 48, bottom: 0),
                        padding: const EdgeInsets.only(left: 32),
                        decoration: BoxDecoration(
                          color: const Color(0xFF4DB4FF),
                          borderRadius: BorderRadius.circular(52),
                        ),
                        child: Row(
                          children: [
                            Image.asset(
                              'assets/images/bt_apple_logo.png',
                              width: 24,
                              height: 24,
                            ),
                            const Padding(
                                padding: EdgeInsets.only(left: 16),
                                child: Text(
                                  'Sign in with Apple',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color(0xFFFFFFFF),
                                  ),
                                ))
                          ],
                        ),
                      ),
                      onTap: () async {
                        autoLogin() async {
                          EasyLoading.show(status: 'Loading...');
                          try {
                            final credential = await SignInWithApple.getAppleIDCredential(
                              scopes: [
                                AppleIDAuthorizationScopes.email,
                                AppleIDAuthorizationScopes.fullName,
                              ],
                            );
                            model.login(3, credential.identityToken ?? '', (success, msg) {
                              if (success) {
                                GetIt.instance<BtAppRouter>().replaceAll([const HostMainRoute()]);
                              }
                              EasyLoading.showToast(msg);
                            });
                          } catch (e) {
                            EasyLoading.dismiss();
                          }
                        }

                        if (!model.isAgreed) {
                          showTermOfUseAndPrivacyPolicyDialog(context, (agree) {
                            if (agree) {
                              model.setAgreed(agree);
                              autoLogin();
                            }
                          });
                          return;
                        }

                        autoLogin();
                      },
                    ),
                    InkWell(
                      child: Container(
                        height: 54,
                        margin: const EdgeInsets.only(left: 48, top: 32, right: 48, bottom: 46),
                        padding: const EdgeInsets.only(left: 32),
                        decoration: BoxDecoration(
                          color: const Color(0xFFFFFFFF),
                          borderRadius: BorderRadius.circular(52),
                        ),
                        child: Row(
                          children: [
                            Image.asset(
                              'assets/images/bt_icon_quick.png',
                              width: 24,
                              height: 24,
                            ),
                            const Padding(
                                padding: EdgeInsets.only(left: 45),
                                child: Text(
                                  'Fast Login',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color(0xFF202020),
                                  ),
                                ))
                          ],
                        ),
                      ),
                      onTap: () async {
                        autoLogin() async {
                          EasyLoading.show(status: 'Loading...');
                          String deviceId = await getDeviceId();
                          model.login(4, deviceId, (success, msg) {
                            if (success) {
                              GetIt.instance<BtAppRouter>().replaceAll([const HostMainRoute()]);
                            }
                            EasyLoading.showToast(msg);
                          });
                        }

                        if (!model.isAgreed) {
                          showTermOfUseAndPrivacyPolicyDialog(context, (agree) {
                            if (agree) {
                              model.setAgreed(agree);
                              autoLogin();
                            }
                          });
                          return;
                        }

                        autoLogin();
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 59),
                      child: Row(
                        children: [
                          InkWell(
                              child: Image.asset(
                                model.isAgreed
                                    ? 'assets/images/bt_icon_checked.png'
                                    : 'assets/images/bt_icon_check.png',
                                width: 16,
                                height: 16,
                              ),
                              onTap: () {
                                model.setAgreed(!model.isAgreed);
                              }),
                          const Padding(
                              padding: EdgeInsets.only(left: 8),
                              child: Text(
                                'By using our App you agree with our',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0xFFFFFFFF),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 83),
                      child: Row(
                        children: [
                          InkWell(
                              child: const Text(
                                'Term of Use',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0xFF4DB4FF),
                                  decoration: TextDecoration.underline,
                                  decorationColor: Colors.blue,
                                  decorationStyle: TextDecorationStyle.solid,
                                ),
                              ),
                              onTap: () {
                                BtLogPvManger.stat(page: BtLogPages.terms);
                                context.router.navigate(WebViewRoute(
                                    title: 'Terms and Conditions',
                                    webUrl: 'https://h5.heeru.xyz/termConditions.html'));
                              }),
                          const Text(
                            'and',
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0xFFFFFFFF),
                            ),
                          ),
                          InkWell(
                              child: const Text(
                                'Privacy Policy.',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Color(0xFF4DB4FF),
                                  decoration: TextDecoration.underline,
                                  decorationColor: Colors.blue,
                                  decorationStyle: TextDecorationStyle.solid,
                                ),
                              ),
                              onTap: () {
                                BtLogPvManger.stat(page: BtLogPages.privacy);
                                context.router.navigate(WebViewRoute(
                                    title: 'Privacy Policy',
                                    webUrl: 'https://h5.heeru.xyz/privacyPolicy.html'));
                              }),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
